package com.dayuanit.dy15.ebook.bookshop.runner;

import com.dayuanit.dy15.ebook.bookshop.dto.CommodityHomeDTO;
import com.dayuanit.dy15.ebook.bookshop.entity.Commodity;
import com.dayuanit.dy15.ebook.bookshop.mapper.CommodityMapper;
import com.dayuanit.dy15.ebook.bookshop.redis.RedisService;
import com.dayuanit.dy15.ebook.bookshop.service.NavigationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class RedisRunner implements ApplicationRunner {

    @Autowired
    private NavigationService navigationService;

    @Resource(name = "redisServiceTempleImpl")
    private RedisService redisService;

    @Autowired
    private CommodityMapper commodityMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("RedisRunner()");
        //将导航栏数据缓存到redis

        navigationService.listAllNavigation();

        //首页商品 查询商品top20
        List<CommodityHomeDTO> commodityHomeDTOS = redisService.zrevRange(0, 20);
        if (!commodityHomeDTOS.isEmpty()) {
            return;
        }

        List<Commodity> commodities = commodityMapper.listTop20();
        commodities.forEach(commodity -> {
            redisService.addHomeBook(1, String.valueOf(commodity.getId()));
        });

        System.out.println("首页商品预热成功");

    }
}
